package com.dinghui.salary.interceptor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.auth0.jwt.interfaces.Claim;
import com.dinghui.salary.enums.ResponseStatusEnum;
import com.dinghui.salary.exception.CommonException;
import com.dinghui.salary.exception.CustomException;
import com.dinghui.salary.pojo.User;
import com.dinghui.salary.service.UserService;
import com.dinghui.salary.utils.*;
import com.dinghui.user.management.service.UserBiz;
import com.dinghui.user.management.vo.UserInfoVO;
import com.dinghui.user.management.vo.Users;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Optional;

/**
 * @author tanrentao
 * @date 2021-09-06
 * @desc 接口认证拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

//    @Reference(check = false)
//    private UserBiz userBiz;

    @Reference(version = "2.0.0")
    UserService userService;

    @Autowired
    private RedisOperator redisOperator;


    /**
     * 拦截请求，在访问controller调用之前
     * @param request
     * @param response
     * @param handler
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // casSessionId
        Cookie cookie = CookieUtils.getCookie(request, "casSessionId");
        if (cookie != null) {
            String s = redisOperator.get(cookie.getValue() + ":user");
            User user = JsonUtils.jsonToPojo(s, User.class);
            LocalUser.set(user);
            return true;
        } else {
            String bearerToken = request.getHeader("Authorization");
            if (StringUtils.isEmpty(bearerToken)) {
                CommonException.display(ResponseStatusEnum.UN_AUTHENTICATED);
            }

            if (!bearerToken.startsWith("Bearer")) {
                CommonException.display(ResponseStatusEnum.UN_AUTHENTICATED);
            }
            String tokens[] = bearerToken.split(" ");
            if (!(tokens.length == 2)) {
                CommonException.display(ResponseStatusEnum.UN_AUTHENTICATED);
            }
            String token = tokens[1];
            Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
            Map<String, Claim> map = optionalMap
                    .orElseThrow(() -> new CustomException(ResponseStatusEnum.UN_AUTHENTICATED));

            setToThreadLocal(map);
            return true;
        }
    }

    /**
     *
     * 请求访问controller之后，渲染视图之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     *
     * 请求访问controller之后，渲染视图之后
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LocalUser.clear();
    }

    // 查询用户信息
    private void setToThreadLocal(Map<String,Claim> map) {
        Integer userId = map.get("userId").asInt();
        User user = userService.selectUserById(userId);
        LocalUser.set(user);
    }
}
